import re

from loguru import logger

from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.school.processor.base_processor import BaseProcessor
from com.arcfox.util.muilty_coroutine_util import concurrency


class HandMajorScoreProcessor(BaseProcessor):
    def __init__(self):
        self.subject_map = {
            "1": "理科", "2": "文科", "3": "综合", "4": "艺术类", "5": "体育类", "25": "艺术文", "24": "体育理",
            "2073": "物理", "2074": "历史", "32": "蒙授文科", "33": "蒙授理科", "138": "函授美术", "26": "艺术理",
            "1079": "3+证书", "2234": "学考"
        }

    async def parse_and_save_data(self, task, province_name, year, result_json):
        logger.info(result_json)
        result_data = result_json['data']
        tasks = []
        for item in result_data['item']:
            min_rank = item['min_section']
            min_score = item['min']
            if min_rank == "-":
                min_rank = None
            if min_score == "-":
                min_score = None
            tasks.append({
                "province": province_name, "score_year": year,
                "subject_item": self.subject_map[str(item['type'])], "batch_name": item['local_batch_name'],
                "major_name": item['spname'], "min_score": min_score,
                "major_std_name": self.process_major_name(item['spname']),
                "min_rank": min_rank, "enroll_count": 0,
                "university_name": task['name'], "university_uid": task['uid']
            })
        await self.__save(tasks=tasks)

    def process_major_name(self, major_name):
        if major_name:
            results = re.split(r'[(（]', major_name)
            major_std_name = results[0]
            return major_std_name
        return None

    @concurrency(5)
    async def __save(self, **params):
        task = params['task']
        mapping = db.MysqlMapping("tb_major_score")
        if await self.check_exist(mapping, task):
            logger.info("数据已存在!")
        else:
            await mapping.insert(task)

    async def check_exist(self, mapping, data):
        condition = {
            "university_uid": data['university_uid'],
            "province": data['province'],
            "score_year": data['score_year'],
            "batch_name": data['batch_name'],
            "major_name": data['major_name'],
            "subject_item": data['subject_item']
        }
        result = await mapping.query(condition, ["id"])
        if result:
            return result[0][0]